<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="demo-form-inline" size="small">
        <el-form-item label="">
          <el-input v-model="searchForm.cate_name" placeholder="请输入分类名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="searchForm.is_show" placeholder="请选择" clearable>
            <el-option label="已下架" value="0"></el-option>
            <el-option label="已上架" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.stop="search(true)">搜索</el-button>
          <el-button type="success" @click.stop="search">刷新</el-button>
          <el-button type="warning" @click.stop="add">添加</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="multiOff" style="margin-bottom:10px">批量下架</el-button>
      <el-table :data="table" border size="small" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column type="expand" width="100" label="展开项">
          <template slot-scope="props">
            <el-row>
              <el-col :span="24">详情： {{props.row.detail}}</el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="cate_name" label="分类">
          <template slot-scope="scope">
            <span v-if="scope.row.cate_type ===1"> {{scope.row.cate_name}}---普通</span>
            <span v-else> {{scope.row.cate_name}}---套餐</span>
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="名称"></el-table-column>
        <el-table-column label="pic" width="125">
          <template slot-scope="scope">
            <el-image style="width: 50px; height: 50px" :src="scope.row.pic" fit="fill" :preview-src-list="[scope.row.pic]"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="售价"></el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
        <el-table-column prop="meat_num" label="荤菜规格">
          <template slot-scope="scope">
            <span v-if="scope.row.cate_type == 2">
              <el-button type="text" @click.stop="editNum('meat_num',scope.row)">{{scope.row.meat_num}}</el-button>
            </span>
            <span v-else style="color:#F56C6C">
              ---
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="veg_num" label="素菜规格">
          <template slot-scope="scope">
            <span v-if="scope.row.cate_type == 2">
              <el-button type="text" @click.stop="editNum('veg_num',scope.row)">{{scope.row.veg_num}}</el-button>
            </span>
            <span v-else style="color:#F56C6C">
              ---
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="detail" label="是否售罄">
          <template slot-scope="scope">
            <span>
              <el-tooltip :content="scope.row.is_out == 1 ? '售罄': '未售罄'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.is_out" :active-value="1" :inactive-value="0" @change="changeGoodsStatus(scope.row,'is_out')">
                </el-switch>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="detail" label="是否上架">
          <template slot-scope="scope">
            <span>
              <el-tooltip :content="scope.row.is_show == 0 ? '下架': '上架'" placement="top" :enterable="false">
                <el-switch active-color="#13ce66" v-model="scope.row.is_show" :active-value="1" :inactive-value="0"
                  @change="changeGoodsStatus(scope.row,'is_show')">
                </el-switch>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="150"></el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="edit(scope.row.id)">编辑</el-button>
            <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page"
          :page-sizes="[10,20,30,40]" :page-size="searchForm.limit" layout="total, sizes, prev, pager, next, jumper" :total="count">
        </el-pagination>
      </div>
      <el-dialog title="添加商品" :visible.sync="addVisible" width="500px" :before-close="handleClose('addForm')">
        <el-form ref="addForm" :model="addForm" label-width="140px" size="small" :rules="rules">
          <el-form-item label="商品分类" prop="cate_id">
            <el-select v-model="addForm.cate_id" clearable placeholder="选择商品分类" style="width:100%">
              <el-option v-for="(item) in cateList" :key="item.id" :label="item.name + '---' + (item.type === 1? '普通' : '套餐')"
                :value="item.id + '-' + item.type">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="addForm.name" placeholder="选择商品名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload ref="addPic" name="image" :action="action" :before-upload="beforeUpload"
              :on-success="((response, file, fileList)=>{handleSuccess(response, file, fileList,'addPic')})" :on-error="handleError"
              :before-remove="beforeRemove" :file-list="fileList" list-type="picture" :data="imgData" :limit="1" :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input-number v-model="addForm.price" :min="0.1" :precision="2" label="商品价格"></el-input-number>
          </el-form-item>
          <el-form-item label="商品库存" prop="stock">
            <el-input-number v-model="addForm.stock" :min="1" :precision="0" label="商品库存"></el-input-number>
          </el-form-item>
          <el-form-item label="详情" prop="detail">
            <el-input v-model="addForm.detail" type="textarea" maxlength="255" show-word-limit></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('addVisible', 'addForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('addVisible','addForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="编辑商品" :visible.sync="editVisible" width="500px" :before-close="handleClose('editForm')">
        <el-form ref="editForm" :model="editForm" label-width="140px" size="small" :rules="rules">
          <el-form-item label="商品分类" prop="cate_id">
            <el-select v-model="editForm.cate_id" clearable placeholder="选择商品分类" style="width:100%">
              <el-option v-for="(item) in cateList" :key="item.id" :label="item.name + '---' + (item.type === 1? '普通' : '套餐')"
                :value="item.id + '-' + item.type">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="editForm.name" placeholder="选择商品名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload ref="editpic" name="image" :action="action" :before-upload="beforeUpload"
              :on-success="((response, file, fileList)=>{handleSuccess(response, file, fileList,'editpic')})" :on-error="handleError"
              :before-remove="beforeRemove" :file-list="fileList" list-type="picture" :data="imgData" :limit="1" :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input-number v-model="editForm.price" :min="0.1" :precision="2" label="商品价格"></el-input-number>
          </el-form-item>
          <el-form-item label="商品库存" prop="stock">
            <el-input-number v-model="editForm.stock" :min="1" :precision="0" label="商品库存"></el-input-number>
          </el-form-item>
          <el-form-item label="详情" prop="detail">
            <el-input v-model="editForm.detail" type="textarea" maxlength="255" show-word-limit></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible','editForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import { editNum, delImg, goodsList, changeGoodsStatus, findCateList, goodsOnly, deleteGoods, addGoods, editGoods, multiOff } from '@/network/api.js'

export default {
  name: 'goods',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        cate_name: '',
        is_show: ''
      },
      action: process.env.NODE_ENV === 'development' ? 'http://dxsd.test.com/school/upload_img' : '/school/upload_img',
      count: 0, // 总记录数
      table: [],
      multipleSelection: [], // 列表左侧选中
      cateList: [],
      imgData: {}, // 上传图片格外信息
      imgurl: '', // 上传以后图片路径
      fileList: [], // 上传列表
      type: '', // 操作类型 add edit
      addForm: {
        name: '', // 名称
        pic: '', // pic
        cate_id: '',
        price: 0.1,
        stock: 1,
        detail: ''
      }, // 添加的表单
      editForm: {
        id: 0,
        name: '', // 名称
        pic: '', // pic
        cate_id: '',
        price: 0.1,
        stock: 1,
        detail: ''
      }, // 编辑的表单
      addVisible: false, // 添加表单
      editVisible: false, // 编辑表单
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        cate_id: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        stock: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        detail: [{ required: true, message: '请输入商品详情', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.search()
  },
  computed: {},
  methods: {
    async search(pageInit = false) {
      try {
        if (pageInit === true) {
          this.searchForm.page = 1
        }
        const rtn = await goodsList(this.searchForm)
        this.table = rtn.data.list
        this.count = rtn.data.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 每页条数变化
    handleSizeChange(val) {
      this.searchForm.limit = val
      this.search()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.search()
    },
    // 上传成功
    handleSuccess(response, file, fileList, type) {
      if (response.code !== 200) {
        this.$message.error(response.msg)
        this.$refs[type].clearFiles() // 删除预览
      } else {
        this.imgurl = response.data
      }
    },
    // 上传失败
    handleError() {
      this.$message.error('上传失败')
    },
    // 上传前
    beforeUpload(file) {
      // 判断文件类型
      const imageType = ['image/png', 'image/jpeg', 'image/jpeg']
      if (imageType.indexOf(file.type) === -1) {
        this.$message.error('请上传png|jpg|jpeg图片')
        return false
      }
      this.imgData.token = this.$storage.get('token')
    },
    // 删除前
    async beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        // 移除方法
        try {
          const formdata = {
            imgurl: this.imgurl,
            type: 2,
            token: this.$storage.get('token')
          }
          if (this.type === 'edit') {
            formdata.id = this.editForm.id
          }
          await delImg(formdata)
          if (this.type === 'edit') {
            this.editForm.pic = ''
          } else {
            this.addForm.pic = ''
          }
          this.imgurl = ''
        } catch (e) {
          this.$message.error(e.message)
          return Promise.reject(new Error(e.message))
        }
      }
    },
    // 超出上传个数
    handleExceed(files, fileList) {
      this.$message.error('已有pic图片请先删除')
    },
    // 列表左侧选中
    handleSelectionChange(val) {
      this.multipleSelection = []
      val.forEach(item => {
        this.multipleSelection.push(item.id)
      })
    },
    // 批量下架
    async multiOff() {
      if (this.multipleSelection.length === 0) {
        return this.$message.error('请至少选中一条数据')
      }
      try {
        await multiOff({ ids: this.multipleSelection })
        this.search()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加商品
    async add() {
      try {
        const rtn = await findCateList({})
        this.type = 'add'
        this.addVisible = true
        this.$nextTick(() => {
          this.cateList = rtn.data
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 编辑商品
    async edit(id) {
      try {
        const cateRtn = await findCateList({})
        const rtn = await goodsOnly({ id })
        this.type = 'edit'
        this.editVisible = true
        this.fileList = []
        this.$nextTick(() => {
          this.cateList = cateRtn.data
          this.editForm = rtn.data
          if (rtn.data.pic !== '') {
            this.fileList.push({ url: rtn.data.pic })
            this.imgurl = rtn.data.pic
          }
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 删除
    async del(id) {
      try {
        await deleteGoods({ id })
        this.search()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    async changeGoodsStatus(row, name) {
      try {
        await changeGoodsStatus({ id: row.id, name, status: row[name] })
      } catch (e) {
        row[name] = row[name] === 1 ? 0 : 1
        this.$message.error(e.message)
      }
    },
    // 编辑规格数量
    editNum(name, row) {
      this.$prompt('请输入规格数量', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1-9][0-9]{0,}$/,
        inputPlaceholder: row[name],
        inputErrorMessage: '请输入合法的数字'
      })
        .then(async ({ value }) => {
          try {
            await editNum({ id: row.id, name, num: value })
            row[name] = value
          } catch (e) {
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          this.$message.warning('您取消了这次操作')
        })
    },
    // 关闭弹出前操作(不包括取消按钮)
    handleClose(formName) {
      return done => {
        this.$refs[formName].resetFields()
        this.fileList = []
        this[formName].pic = ''
        this.imgurl = ''
        this.inputVisible = false
        this.inputValue = ''
        done()
      }
    },
    // 取消按钮
    close(visibleName, formName) {
      this.$refs[formName].resetFields()
      this[visibleName] = false
      this[formName].pic = ''
      this.imgurl = ''
      this.fileList = []
      this.inputVisible = false
      this.inputValue = ''
    },
    send(visibleName, formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          switch (formName) {
            case 'addForm': // 添加表单
              try {
                this.addForm.pic = this.imgurl
                if (this.addForm.pic === '') {
                  return this.$message.error('请上传商品图片')
                }
                await addGoods(this.addForm)
                this.close('addVisible', 'addForm')
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'editForm': // 编辑表单
              try {
                this.editForm.pic = this.imgurl
                if (this.editForm.pic === '') {
                  return this.$message.error('请上传商品图片')
                }
                await editGoods(this.editForm)
                this.close('editVisible', 'editForm')
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
